package com.example.controller;


import com.example.pojo.Department;
import com.example.pojo.Employee;
import com.example.service.DepartmentServiceImpl;
import com.example.service.EmployeeServiceImpe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.Collection;

@Controller
public class EmployeeController {

    @Autowired
    private EmployeeServiceImpe employeeServiceImpe;
    @Autowired
    private DepartmentServiceImpl departmentServiceImpl;

    @RequestMapping("/emps")
    public String list(Model model) {
        Collection<Employee> employees = employeeServiceImpe.getAll();
        model.addAttribute("emps", employees);
        return "emp/list";
    }

    @GetMapping("/emp")
    public String toAddpage(Model model) {
        //查出所有部门的信息
        Collection<Department> departments = departmentServiceImpl.getDepartments();
        model.addAttribute("departments", departments);
        return "emp/add";
    }

    @PostMapping("/emp")
    public String addEmp(Employee employee) {
        //保存员工信息
        employeeServiceImpe.save(employee);
        return "redirect:/emps";
    }

    //员工的修改页面
    @GetMapping("/emp/{id}")
    public String toUpdateEmp(@PathVariable("id") Integer id, Model model) {
        //查出原来的数据
        Employee employee = employeeServiceImpe.getEmployeeById(id);
        model.addAttribute("emp", employee);
        //查出所有部门的信息
        Collection<Department> departments = departmentServiceImpl.getDepartments();
        model.addAttribute("departments", departments);
        return "emp/update";
    }

    //修改员工信息
    @PostMapping("/updateEmp")
    public String updateEmp(Employee employee) {
        employeeServiceImpe.update(employee);
        return "redirect:/emps";
    }

    //删除员工
    @GetMapping("/delemp/{id}")
    public String deleteEmp(@PathVariable("id") Integer id) {
        employeeServiceImpe.delete(id);
        return "redirect:/emps";
    }

    //注销
    @RequestMapping("/logout")
    public String logOut(HttpSession session) {
        session.removeAttribute("loginUser");
        return "index.html";
    }
}
